// pages/undercover/undercover.js


//获取应用实例
const app = getApp();
Page({
  //页面的初始数据
  data: {
    isMaster: app.globalData.isMaster, //是否是房主
    isStart: false, //游戏是否开始
    isdice: false, //是否开始摇
    isLoading: false, //是否加载结果
    isEnd: false, //是否结束
    socketStatus: 'closed', //socket状态
    room_id: 0, //房间id
    ownerId: null, //本人id
    masterId: null, //房主id
    client_id: null,
    holderType: null, //房客类型
    memberList: [], //房间成员信息
    resultList: {}, //结果信息
    tick: null, //计时器
    diceChassis: '掷色子', //按钮文字
    limit: 10, //时间限制
    chassis1: null, //一号色子
    chassis2: null, //二号色子
    all_num: 0 //本人点数
  },

  // 生命周期函数--监听页面加载
  onLoad: function(options) {
    var that = this;
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    that.setData({
      room_id: options.room_id,
      ownerId: app.globalData.userInfoSession.uid
    })
  },

  //生命周期函数--监听页面初次渲染完成
  onReady: function() {
    this.animation1 = wx.createAnimation({
      duration: 20
    });
    this.animation2 = wx.createAnimation({
      duration: 1000,
      delay: 1000
    });
    this.animation3 = wx.createAnimation({
      duration: 1000,
      delay: 1000
    });
    this.animation4 = wx.createAnimation({
      duration: 1000,
      delay: 1000
    })
  },

  // 生命周期函数--监听页面显示
  onShow: function() {
    if (this.data.socketStatus === 'closed') {
      this.openSocket()
    }
  },

  //生命周期函数--监听页面隐藏
  onHide: function() {

  },

  //生命周期函数--监听页面卸载
  onUnload: function() {
    this.closeSocket();
  },

  //用户点击右上角分享
  onShareAppMessage: function() {
    var that = this,
      path = '/pages/main/home/home?jump_dice=' + that.data.room_id + '&type=2'

    return {
      title: '掷色子比大小房间传建好了，快来参与吧~',
      path: path,
      imageUrl: '../../resource/share.png',
      success(res) {
        console.log(res)
      }
    }
  },
  //开始游戏
  startGame() {
    var that = this,
      room_id = that.data.room_id;
    wx.request({
      method: 'post',
      url: app.globalData.path + 'start_dice_game',
      header: {
        'Cookie': "PHPSESSID=" + app.globalData.session_id
      },
      data: {
        room_id: room_id
      },
      success(res) {
        console.log(res);
      }
    })
  },
  //倒计时
  countdown() {
    var that = this,
      limit = that.data.limit,
      room_id = that.data.room_id,
      client_id = that.data.client_id;
    if (limit < 1) {
      clearInterval(that.data.tick)
      wx.request({
        url: app.globalData.path + 'get_dice_point',
        method: 'get',
        header: {
          'Cookie': "PHPSESSID=" + app.globalData.session_id
        },
        data: {
          room_id: room_id,
          client_id: client_id
        },
        success(res) {
          console.log(res)
        }
      })
      that.setData({
        isEnd: true
      })
    } else {
      limit--
      var diceWord = that.data.isdice ? "掷色子" : "掷色子(" + limit + ")";
      that.setData({
        diceChassis: diceWord,
        limit: limit
      });

    }
  },
  //摇色子动画及结果页
  diceChassis() {
    var that = this,
      room_id = that.data.room_id;
    for (var i = 0; i < 24; i++) {
      if (i % 2 == 0) {
        that.animation1.translate(10).step()
      } else {
        that.animation1.translate(-10).step()
      }
    }
    that.animation1.translate(0).step()
    that.animation2.translate(300, -300).opacity(0).step()
    var dis1, dis2, all_num;
    dis1 = Math.ceil(Math.random() * 6)
    dis2 = Math.ceil(Math.random() * 6)
    all_num = dis1 + dis2
    that.setData({
      chassis1: that.result(dis1),
      chassis2: that.result(dis2)
    });
    that.animation3.translate(Math.random() * 20 - 10, Math.random() * 20 - 10).rotate(3600).step()
    that.animation4.translate(Math.random() * 20 - 10, Math.random() * 20 - 10).rotate(3600).step()
    that.setData({
      animation1: that.animation1.export(),
      animation2: that.animation2.export(),
      animation3: that.animation3.export(),
      animation4: that.animation4.export(),
      isdice: true,
      diceChassis: "掷色子",
      all_num: all_num
    });
    wx.request({
      method: 'get',
      url: app.globalData.path + 'shake_dice',
      header: {
        'Cookie': "PHPSESSID=" + app.globalData.session_id
      },
      data: {
        room_id: room_id,
        dice_point: all_num,
        uid: that.data.ownerId
      },
      success(res) {
        console.log(res)
      }
    })
    setTimeout(function() {
      that.setData({
        isLoading: true
      })
    }, 5000);
  },
  //掷色子结果匹配图
  result(num) {
    var r = "../../resource/dice_";
    switch (num) {
      case 1:
        r += "one.png";
        break;
      case 2:
        r += "two.png";
        break;
      case 3:
        r += "three.png";
        break;
      case 4:
        r += "four.png";
        break;
      case 5:
        r += "five.png";
        break;
      case 6:
        r += "six.png";
        break;
    }
    return r;
  },
  //点击关闭按钮再来一局
  againGame() {
    var that = this,
      room_id = that.data.room_id;
    that.animation1.translate(0).step({
      duration: 0
    });
    that.animation2.translate(0).opacity(1).step({
      duration: 0,
      delay: 0
    });
    that.animation3.translate(0).rotate(0).step({
      duration: 0
    });
    that.animation4.translate(0).rotate(0).step({
      duration: 0
    });

    that.setData({
      isLoading: false,
      isEnd: false,
      animation1: that.animation1.export(),
      animation2: that.animation2.export(),
      animation3: that.animation3.export(),
      animation4: that.animation4.export()
    })

    if (that.data.isMaster) {
      wx.request({
        method: 'get',
        url: app.globalData.path + 'again_dice_game',
        header: {
          'Cookie': "PHPSESSID=" + app.globalData.session_id
        },
        data: {
          room_id: room_id
        },
        success(res) {
          console.log(res)
        }
      })
    }
  },

  toggleSocket: function(e) {
    var that = this
    if (that.data.socketStatus == 'closed') {
      that.openSocket()
    } else if (that.data.socketStatus == 'connected') {
    }
  },
  openSocket() {
    var that = this;
    wx.onSocketOpen(() => {
      console.log('WebSocket 已连接')
      setInterval(function() {
        that.sendMessage();
      }, 3000)
      this.setData({
        socketStatus: 'connected',
        waitingResponse: false
      })
    })

    wx.onSocketClose(() => {
      console.log('WebSocket 已经断开')
      if (!this.data.isStart) {
        app.globalData.isMaster = false
      }
      this.setData({
        socketStatus: 'closed'
      })
    })

    wx.onSocketError(error => {
      showWordModal('发生错误', JSON.stringify(error))
      console.error('socket error:', error)
      this.setData({
        loading: false
      })
    })

    // 监听服务器推送消息
    wx.onSocketMessage(message => {
      var obj = JSON.parse(message.data);
      var PL = that.data.memberList;
      console.log(obj, PL);
      var client_id = obj.client_id;
      if (that.data.client_id == null) {
        that.setData({
          client_id: client_id
        })
      }
      if (app.globalData.isMaster) {
        that.setData({
          holderType: 1,
          isMaster: app.globalData.isMaster
        })
      } else {
        that.setData({
          holderType: 2,
          isMaster: app.globalData.isMaster
        })
      }
      switch (obj.type) {
        // 初始化数据
        case 'init':
          wx.request({
            method: 'post',
            url: app.globalData.path + 'enter_dice_room',
            header: {
              'Cookie': "PHPSESSID=" + app.globalData.session_id
            },
            dataType: 'json',
            data: {
              room_id: that.data.room_id,
              type: that.data.holderType,
              client_id: client_id
            },
            success: res => {
              console.log(res)
              if (res.data.status == 0) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000,
                  success: () => {
                    wx.redirectTo({
                      url: '/pages/main/home/home',
                    })
                  }
                });
              }
            },
            error: function(res) {
            }
          })
          break;
          //进入房间
        case 'enter_room':
          if (obj.room_status == 1) {
            that.setData({
              isStart: false
            })
          }
          if (obj.client_list === undefined) { // 房间中的人：新进入房间人的数据
            PL.push({
              client_id: obj.client_id,
              type: 2,
              nickname: obj.nickname,
              avatar_url: obj.avatar_url
            })
            for (var i = 0; i < obj.length; i++) {
              if (obj[i].type == 1) {
                that.setData({
                  masterId: obj[i].uid
                })
              }
            }
            that.setData({
              memberList: PL
            })
            wx.showToast({
              title: obj.nickname + '加入了房间',
              icon: 'none',
              duration: 2000
            })
          } else { // 普通玩家进入房间：此时房间中全部的人员数据
            for (var i = 0; i < obj.client_list.length; i++) {
              if (obj.client_list[i].type == 1) {
                that.setData({
                  masterId: obj.client_list[i].uid
                })
              }
            }
            that.setData({
              memberList: obj.client_list
            })
          }
          break;
          // 退出房间
        case 'exit_room':
          if (that.data.isStart) {
            wx.showToast({
              title: obj.nickname + '掉线了',
              icon: 'none',
              duration: 2000
            })
          } else {
            // 删掉掉线的人的头像
            for (var i = 0; i < PL.length; i++) {
              if (PL[i].client_id == obj.client_id) {
                PL.splice(i, 1);
              }
            }
            that.setData({
              memberList: PL,
            })
            wx.showToast({
              title: obj.nickname + '退出了房间',
              icon: 'none',
              duration: 2000
            })
          }
          break;
          // 游戏中退出房间后重新回到房间
        case 'reconnect_room':
          var old_time = parseInt(obj.old_user.start_time),
            now_time = parseInt(new Date().getTime() / 1000),
            limits = 10 - (now_time - old_time),
            tick = that.data.tick;
            PL = obj.start_list;
          // 重新对连线的用户进行页面渲染
          wx.showToast({
            title: obj.nickname + '已连线',
            icon: 'none',
            duration: 2000
          })
          for (var i = 0; i < obj.start_list.length; i++) {
            //房主掉线
            if (obj.start_list[i].type == 1) {
              app.globalData.isMaster = true
              that.setData({
                holderType: 1,
                masterId: obj.start_list[i].uid, //房主ID
                isMaster: app.globalData.isMaster
              })
            }
          }
          for (var i = 0; i < obj.start_list.length; i++) {
            if (obj.start_list[i].uid == obj.uid) {
              clearInterval(tick)
              if (limits > 0 && obj.start_list[i].dice_point == "") {
                that.setData({
                  memberList: PL,
                  isStart: true,
                  limit: limits,
                  diceChassis: "掷色子(" + limits + ")"
                })
                tick = setInterval(that.countdown, 1000)
                that.setData({
                  tick: tick
                })
              } else if (limits > 0 && obj.start_list[i].dice_point != "") {
                that.setData({
                  memberList: PL,
                  isStart: true,
                  limit: limits,
                  isdice: true,
                  isLoading: true,
                  diceChassis: "掷色子"
                })
                tick = setInterval(that.countdown, 1000)
                that.setData({
                  tick: tick
                })
              } else if (limits < 1) {
                wx.request({
                  url: app.globalData.path + 'get_dice_point',
                  method: 'get',
                  header: {
                    'Cookie': "PHPSESSID=" + app.globalData.session_id
                  },
                  data: {
                    room_id: that.data.room_id,
                    client_id: that.data.client_id
                  },
                  success(res) {
                    console.log(res)
                  }
                })
                that.setData({
                  memberList: PL,
                  isStart: true,
                  isdice: true,
                  isLoading: true,
                  isEnd: true
                })
              }
            }
          }
          break;
          //游戏未开始，房主掉线
        case 'change_homeowner':
          app.globalData.isMaster = false;
          that.setData({
            isMaster: app.globalData.isMaster
          })
          PL = obj.client_list
          for (var i = 0; i < PL.length; i++) {
            if (PL[i].type == 1) {
              app.globalData.isMaster = true;
              that.setData({
                holderType: 1,
                isMaster: app.globalData.isMaster,
                masterId: PL[i].uid
              })
            }
          }
          that.setData({
            memberList: PL,
          })
          wx.showToast({
            title: '房主退出了房间',
            icon: 'none',
            duration: 2000
          })
          break;
          //开始游戏
        case 'start_game':
          var limit = that.data.limit,
            tick = that.data.tick;
          tick = setInterval(that.countdown, 1000)
          that.setData({
            isStart: true,
            diceChassis: "掷色子(" + limit + ")",
            tick: tick
          })
          break;
          //摇色子
        case "shake_dice":
          setTimeout(function() {
            that.setData({
              isLoading: true
            })
          }, 5000);
          break;
          //获取点数结果
        case "get_dice_point":
          that.setData({
            resultList: obj.list
          })
          break;
          // 再来一次游戏
        case 'again_game':
          PL = obj.client_list
          that.animation1.translate(0).step({
            duration: 0
          });
          that.animation2.translate(0).opacity(1).step({
            duration: 0,
            delay: 0
          });
          that.animation3.translate(0).rotate(0).step({
            duration: 0
          });
          that.animation4.translate(0).rotate(0).step({
            duration: 0
          });
          that.setData({
            animation1: that.animation1.export(),
            animation2: that.animation2.export(),
            animation3: that.animation3.export(),
            animation4: that.animation4.export(),
            tick: null, //计时器
            diceChassis: '掷色子', //按钮文字
            limit: 10, //时间限制
            chassis1: null, //一号色子
            chassis2: null, //二号色子
            all_num: 0, //本人点数
            memberList: PL,
            isLoading: false,
            isEnd: false,
            isStart: false, //游戏是否开始
            isdice: false, //是否开始摇
            resultList: {} //结果信息
          })
          for (var i = 0; i < PL.length; i++) {
            if (PL[i].type == 1) {
              app.globalData.isMaster = true;
            }
          }
          break;
      }
    })

    //创建socket链接
    wx.connectSocket({
      url: 'ws://192.168.1.189:7272',
      header: {},
      method: 'GET'
    })
  },

  closeSocket() {
    var that = this
    if (that.data.socketStatus === 'connected') {
      wx.closeSocket({
        success: () => {
          that.setData({
            socketStatus: 'closed',
            isMaster: false
          })
          app.globalData.isMaster = false;
        }
      })
    }
  },

  sendMessage() {
    if (this.data.socketStatus === 'connected') {
      console.log('向后台发送一条请求');
      wx.sendSocketMessage({
        data: '{"type":"heart","message":"heart_message..."}'
      })
    }
  },

  getReturnMsg(type) {

  }
})